import markdown
from django.db.models import Q
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, get_object_or_404, redirect
from django.urls import reverse

from django.contrib.auth import authenticate, login, logout
from django.views.decorators.csrf import csrf_exempt

from blog import models
from blog.models import Article, Category, Tag, BlogComment, Author
from tools.page_tool import page_tools
from django.db.models.aggregates import Count

from tools.send_mail_tool import send_email_code
from .forms import UserRegisterForm, UserLoginForm


def page_not_found(request, exception, template_name='404.html'):
    return render(request, template_name)

@csrf_exempt
def register(request):
    if request.method == 'POST':
        user_register_form = UserRegisterForm(request.POST)
        if user_register_form.is_valid():
            email = user_register_form.cleaned_data['email']
            password = user_register_form.cleaned_data['password']
            c_password = user_register_form.cleaned_data['c_password']
            if password == c_password:
                user_list = Author.objects.filter(Q(username=email) | Q(email=email))
                if user_list:
                    return render(request, 'register.html', {
                        'msg': '用户名已经存在(游戏或者用户名已经被使用)，请重新注册'
                    })
                else:
                    user = Author()
                    user.username = email
                    user.set_password(password)
                    user.email = email
                    user.is_active = False
                    user.save()
                    return redirect(reverse("blog:user_login"))
            else:
                return render(request, 'register.html', {
                    'msg': '密码不一致'
                })
        else:
            return render(request, 'register.html', {
                'msg': '数据都不能为空'
            })
    else:
        return render(request, 'register.html')


def user_logout(request):
    logout(request)
    request.session.flush()
    return redirect(reverse('blog:user_login'))


# class Login(APIVIEW)
@csrf_exempt
def user_login(request):
    if request.method == 'POST':
        user_login_form = UserLoginForm(request.POST)
        if user_login_form.is_valid():
            email = user_login_form.cleaned_data['email']
            password = user_login_form.cleaned_data['password']
            user = authenticate(username=email, password=password)
            if user:
                if user.is_active == True:
                    login(request, user)
                    return redirect(reverse('blog:index'))
                else:
                    return render(request, 'login.html', {
                        'msg': '您的账号尚未激活'
                    })
            else:
                return render(request, 'login.html', {
                    'msg': '账号或密码错误'
                })

    else:
        return render(request, 'login.html')


def mulu(request):
    all_category = models.Category.objects.all()
    category_list = Category.objects.annotate(num_arts=Count('articles'))
    content = {
        'all_category': all_category,
        'category_list': category_list,
    }
    return content


def index(request):
    # content = mulu(request)
    all_category = models.Category.objects.all()
    category_list = Category.objects.annotate(num_arts=Count('articles'))
    content = {
        'all_category': all_category,
        'category_list': category_list,
        'index_active': 'am-active',
        'category_name': '文章分类'
    }
    return render(request, 'index.html', content)


# 文章列表
def article_list(request, category):
    list = Article.objects.filter(category__name=category).order_by('-created_time')
    content = mulu(request)
    content['list'] = list

    page = request.GET.get('page', 1)
    per_page = request.GET.get('per_page', 10)
    page_object, paginator = page_tools(list, page, per_page)
    # content['page_object'] = page_object
    # content['paginator'] = paginator
    # content['page_range'] = paginator.page_range
    # content['list_active'] = 'am-active'
    # content['category_name'] = category
    data = {
        'page_object': page_object,
        'paginator': paginator,
        'page_range': paginator.page_range,
        'list_active': 'am-active',
        'category_name': category,
        'category_active': 'color: #10D07A'
    }
    content.update(data)
    return render(request, 'list.html', content)


# 文章详情
def article_datail(request, category, id):
    article_all = Article.objects.all()
    article_obj = article_all.filter(category__name=category).filter(pk=id).first()
    # 获取评论
    blogcomment_obj = BlogComment.objects.filter(article=article_obj).all().order_by('-created_time')
    # 点击次数
    article_obj.views = article_obj.views + 1
    article_obj.save()

    # 将markdown语法渲染成html样式
    article_obj.body = markdown.markdown(article_obj.body,
                                         extensions=[
                                             # 包含 缩写、表格等常用扩展
                                             'markdown.extensions.extra',
                                             # 语法高亮扩展
                                             'markdown.extensions.codehilite',
                                         ])
    all_category = models.Category.objects.all()
    category_counts = all_category.count()

    content = mulu(request)

    previous_obj = article_all.filter(pk=(id - 1)).first()
    next_obj = article_all.filter(pk=(id + 1)).first()

    data = {

        'article_obj': article_obj,
        'blogcomment_obj': blogcomment_obj,
        'all_category': all_category,
        'category_counts': category_counts,
        'category_name': category,
        'category_active': 'color: #10D07A',
        'previous_obj': previous_obj,
        'next_obj': next_obj,
    }
    data.update(content)
    return render(request, 'article_detail.html', data)


# 文章评论
def post_comment(request, post_id):
    post = get_object_or_404(Article, pk=post_id)
    if request.method == 'POST':
        body = request.POST.get('comment_content', None)
        if len(body) < 5:
            return JsonResponse({'res': '评论字数不能低于5个'})
        comment_obj = BlogComment()
        comment_obj.body = body
        comment_obj.article = post
        comment_obj.save()
        return JsonResponse({'res': 1})
    else:
        return JsonResponse({'res': 0})


# 搜索
def search(request):
    search_keyword = request.GET.get('search')  # 获取搜索的关键词
    list = Article.objects.filter(title__icontains=search_keyword).order_by('-created_time')  # 获取到搜索关键词通过标题进行匹配
    # all_catagory = Category.objects.all()
    page = request.GET.get('page', 1)
    per_page = request.GET.get('per_page', 10)
    page_object, paginator = page_tools(list, page, per_page)

    data = {
        'page_object': page_object,
        'paginator': paginator,
        'page_range': paginator.page_range,
        'search_count': list.count(),
        'search_keyword': search_keyword,
        'category_name': '文章分类',
        'category_active': 'color: #10D07A',
    }

    content = mulu(request)
    data.update(content)

    return render(request, 'search.html', data)


# 所有文章
def all_articles(request):
    all_art = models.Article.objects.all().order_by('-created_time')
    page = request.GET.get('page', 1)
    per_page = request.GET.get('per_page', 3)
    page_object, paginator = page_tools(all_art, page, per_page)
    data = {
        'page_object': page_object,
        'paginator': paginator,
        'page_range': paginator.page_range,
        'all_articles_active': 'color: #10D07A',
        'category_name': '文章分类'
    }
    content = mulu(request)
    data.update(content)
    return render(request, 'list.html', data)


# 图片
def img(request):
    data = {
        'all_imgs_active': 'color: #10D07A',
        'category_name': '文章分类'
    }
    content = mulu(request)
    data.update(content)
    return render(request, 'img.html', data)
